package common

import (
	"context"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/go-log"
)

type OrgFetchFunc func(ctx context.Context, lwa db.AmazonLwaCommon, sdk *advertising.Client)

func TravelAmazonClients(ctx context.Context, h OrgFetchFunc) {
	index := 0

	for {
		select {
		case <-ctx.Done():
			return
		default:
			c, err := GetClient(index)
			if err != nil {
				return
			}
			index++
			fetchClientForOrg(ctx, c, h)
		}
	}
}

func fetchClientForOrg(ctx context.Context, c db.AmazonLwa, h OrgFetchFunc) {
	defer func() {
		if err := recover(); err != nil {
			log.Info(err)
			return
		}
	}()
	if h == nil {
		return
	}
	handler, err := CreateSdk(c)
	if err != nil {
		log.Info(err)
		return
	}
	h(ctx, c.AmazonLwaCommon, handler)
	return
}
